import { Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { StudentStudentProfileEntity } from '../entity/studentProfile';
import { CheckDataEntity } from '../entity/checkData';

/**
 * 学生档案服务
 */
@Provide()
export class StudentStudentProfileService extends BaseService {
  @InjectEntityModel(StudentStudentProfileEntity)
  studentStudentProfileEntity: Repository<StudentStudentProfileEntity>;

  @InjectEntityModel(CheckDataEntity)
  checkDataEntity: Repository<CheckDataEntity>;

  /**
   * 软删除
   * @param id
   */
  async reportSoftDelete(id: number) {
    // console.log('reportSoftDelete', id);
    return this.studentStudentProfileEntity.softDelete(id);
  }

  // 根据学员id返回检查数据
  async getCheckDataByStudentId(studentId: number) {
    const data =  this.checkDataEntity.find({
      where: {
        studentId,
      },
    });
    // 检查数据根据检查时间分组
    const groupData = (await data).reduce((pre, cur) => {
      const key = cur.checkTime.toDateString();
      if (!pre[key]) {
        pre[key] = [];
      }
      pre[key].push(cur);
      return pre;
    }, {});
    // 检查时间是降序
    const keys = Object.keys(groupData);
    keys.sort((a, b) => {
      return new Date(b).getTime() - new Date(a).getTime();
    });
    // 重新排序
    const newGroupData = {};
    keys.forEach(key => {
      newGroupData[key] = groupData[key];
    });
    // 每个检查时间，对应的身体部位，进行对比，显示升降
    Object.keys(newGroupData).forEach(key => {
      const checkDatas = newGroupData[key];
      checkDatas.sort((a, b) => {
        return a.bodyPart - b.bodyPart;
      });
      // 对比身体部位，显示升降
      checkDatas.forEach((item, index) => {
        if (index === 0) {
          item.ascend = 0;
        } else {
          item.ascend = checkDatas[index - 1].bodyPart - item.bodyPart;
        }
      });
    });

    return newGroupData;
  }
}
